<?php

namespace frontend\controllers;

use frontend\models\Cart;
use frontend\models\LoginForm;
use frontend\models\Member;
use frontend\models\Smslimit;
use yii\filters\AccessControl;
use yii\helpers\Url;

use Flc\Alidayu\Client;
use Flc\Alidayu\App;
use Flc\Alidayu\Requests\AlibabaAliqinFcSmsNumSend;


class MemberController extends \yii\web\Controller
{
    public $layout='regest';

    public function behaviors()
    {
        return [
            'acf'=>[
                'class'=>AccessControl::className(),
                'only'=>['login','regist','logout'],
                'rules'=>[
                    [
                        'allow'=>true,
                        'actions'=>['logout','regist'],
                        'roles'=>['@'],
                    ],
                    [
                        'allow'=>true,
                        'actions'=>['login','regist'],
                        'roles'=>['?'],
                    ],
                ]
            ]
        ];
    }

    /**
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * @return string|\yii\web\Response
     */
    public function actionRegist(){
        //实例化表单模型
        $model = new Member();
        //加载并且验证数据
        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            //调用方法注册用户
            if($model->signup()){
                //注册成功后跳转到首页
                \Yii::$app->session->setFlash(true,'注册成功');
                return $this->redirect(Url::home());

            }
        }
        return $this->render('regist',['model'=>$model]);
    }

    /** 发送短信验证码 */
    public function actionSms(){
        //接收传递过来的电话号码
        $tel = \Yii::$app->request->post('tel');
        //实现验证码被涮的方案
        //获取当前手机号码的记录信息
        $smsobj = Smslimit::getsmsObj($tel);
        //调用方法验证该手机号码是否允许发送短信
        if(!$smsobj->validateTel()){
            return  \yii\helpers\Json::encode($smsobj->getErrors());
        }

        //生成手机验证码
        $smsCode  = mt_rand(10000,90000);
        //保存验证码到session中
        \Yii::$app->session->set('tel_'.$tel,$smsCode);


    //echo $smsCode;exit;
// 配置信息
        $config = [
            'app_key'    => '23748011',
            'app_secret' => 'd8aa4520d25c70e5561ce428cb99cbe5',
            // 'sandbox'    => true,  // 是否为沙箱环境，默认false
        ];


// 使用方法一
        $client = new Client(new App($config));
        $req    = new AlibabaAliqinFcSmsNumSend;

        $req->setRecNum($tel)
            ->setSmsParam([
                'code' => $smsCode,
            ])
            ->setSmsFreeSignName('工人网站')
            ->setSmsTemplateCode('SMS_60690213');

        $resp = $client->execute($req);

/*
// 使用方法二
        Client::configure($config);  // 全局定义配置（定义一次即可，无需重复定义）

        $resp = Client::request('alibaba.aliqin.fc.sms.num.send', function (IRequest $req) {
            $req->setRecNum('13312311231')
                ->setSmsParam([
                    'number' => rand(100000, 999999)
                ])
                ->setSmsFreeSignName('叶子坑')
                ->setSmsTemplateCode('SMS_15105357');
        });




*/
// 返回结果
       // VarDumper::dump($resp,10,true);
        //var_dump($resp->result);
        //var_dump($resp->request_id);
        //exit;
        //print_r($resp);
		//echo  $smscode;
        //echo $resp->result->success;

        echo \yii\helpers\Json::HtmlEncode($resp);
    }
    /**
     * @return string|\yii\web\Response
     */
    public function actionLogin()
    {
        //实例化表单模型
        $model = new LoginForm();
        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            //调用方法实现登录
            $rs = $model->login();
            if($rs){
                \Yii::$app->session->setFlash('success','你好!'.$model->username.'登录成功');
                //用户登录成功后同步cookie中的购物车中的信息到购物车数据表中
                //调用方法同购物车的数据
                Cart::synCartCookie();

//                return $this->redirect(Url::home());
                return $this->redirect(Url::home());
            }
        }


        //显示视图
        return $this->render('login',['model'=>$model]);
    }

    /**
     * @return \yii\web\Response
     */
    public function actionLogout(){
        //注销
        if(\Yii::$app->user->logout()){
            \Yii::$app->session->setFlash('success','注销成功');
        }

        return $this->redirect(['member/index']);
    }



}
